'''
康爱保疾病保障计划
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests
from common.helper import Helper
from threading import Thread


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "康爱保疾病保障计划"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA":{

                # 年龄段 1978 - 2019
                "year": [str(i) for i in range(1, 41)],
                # 0 男 1 女 2018 - 1978
                "gender": ["0", "1"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 10w - 50w
                "money": ["100000" if i == 1 else str(i) + "0000" for i in range(10, 55, 5)],
                # 缴费期间 0 趸交 5年 10 年 20年
                "interval": ["0", "5", "10", "20", "30"]

            },
            "planB":{

                # 年龄段 1969 - 1973
                "year": [str(i) for i in range(45, 51)],
                # 0 男 1 女
                "gender": ["0", "1"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 10w - 50w
                "money": ["100000" if i == 1 else str(i) + "0000" for i in range(10, 35, 5)],
                # 缴费期间 0 趸交 5年 10 年 20年
                "interval": ["0", "5", "10", "20"]


            },

            "planC":{

                # 年龄段 1974 - 1978
                "year": [str(i) for i in range(41, 46)],
                # 0 男 1 女
                "gender": ["0", "1"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 10w - 50w
                "money": ["100000" if i == 1 else str(i) + "0000" for i in range(10, 55, 5)],
                # 缴费期间 0 趸交 5年 10 年 20年
                "interval": ["0", "5", "10", "20"]

            },

            "planD":{

                # 年龄段 1965 - 1968
                "year": [str(i) for i in range(51, 55)],
                # 0 男 1 女
                "gender": ["0", "1"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 10w - 50w
                "money": ["100000" if i == 1 else str(i) + "0000" for i in range(10, 35, 5)],
                # 缴费期间 0 趸交 5年 10 年 20年
                "interval": ["0", "5", "10"]


            },
            "planE":{

                # 年龄段 1958-1963
                "year": [str(i) for i in range(56, 61)],
                # 0 男 1 女
                "gender": ["0", "1"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 10w - 50w
                "money": ["100000"],
                # 缴费期间 0 趸交 5年 10 年 20年
                "interval": ["0", "5", "10"]

            }


        }

        for k in plan:
            for v in product( plan[k]["year"],plan[k]["gender"],plan[k]["expire"],plan[k]["money"],plan[k]["interval"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4]))
                self.mysql._conn.commit()
                print("%s写入数据库成功" % self.name)

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        data = {

            "insuredsStr": '[{"birthday": "' + str(2019 - int(dt["year"])) + '-10-01", "sex": "' + dt[
                "gender"] + '", "planInfos": [{"riskCode": "I150", "mainRiskCode": "I150", "planCode": "31", "planPeriod": "' +
                           dt[
                               "expire"] + '", "payType": "0","payEndYearFlag": "", "payEndYear": ' + dt[
                               "interval"] + ', "dutys": [{"dutyCode": "104001", "dutyAmnt": "' + dt[
                               "money"] + '"}]}]}]',
            "isOrder": "0",
            "productID": "35"

        }

        data = urlencode(data).replace('+', '')

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=data)

        if '保费计算_[0]被保人_未查询到对应费率，无法计算保费！' in r.text:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("产品价格更新失败:", dt["id"])

        else:

            price = Helper.decimalParse(r.json()["data"]["data"]["premiun"])

            data = {

                "name": self.name,
                "price": price,
                "id": dt["id"]
            }

            mysql.updatePrice(data)



    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):

        threads = []

        for i in range(5):

            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()

            threads.append(t)

        for t in threads:
            t.join()

